package yf.mall.service.impl;

import yf.mall.common.Const;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.AccountTypeEnum;
import yf.mall.enums.CourseCardStatusEnum;
import yf.mall.enums.CourseStatusEnum;
import yf.mall.enums.SignStatusEnum;
import com.yf.response.RRException;
import yf.mall.service.AccountService;
import yf.mall.service.MallStoreService;
import yf.mall.service.NoticeService;
import yf.mall.vo.CourseSumVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import yf.mall.service.CourseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 讲堂Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Mon Oct 21 08:39:57 CST 2019
 */
@Service
public class CourseServiceImpl extends BaseServiceImpl<CourseEntity> implements CourseService {

    private CourseDao courseDao;


    @Autowired
    public void setDao(CourseDao courseDao) {
        this.courseDao = courseDao;
        super.setBaseDao(courseDao);
    }


    /**
     *
     *   @Override
     *     public List<UserVo> queryListVo(UserVo userVo) {
     *         return userDao.queryListVo(userVo);
     *     }
     *
     *     @Override
     *     public UserVo getVo(Long id) {
     *         return userDao.getVo(id);
     *     }

     @Override List<CourseVo> queryListVo(CourseVo courseVo){
     return courseDao.queryListVo(courseVo);
     }

     @Override CourseVo getVo(Long id){
     return courseDao.getVo(id);
     }
     **/


    /**
     * 内部方法
     **/

    void payByAccount(CourseCardEntity courseCardEntity) {
        if (courseCardEntity.getStatus().equals(CourseCardStatusEnum.ACTIVE.getIndex())) {
            throw new RRException("请勿重复激活!");
        }
        //扣减代金券
        accountService.transfer(courseCardEntity.getCreateUserId(), Const.ADMIN_ID, AccountTypeEnum.CASH.getIndex(), courseCardEntity.getAmount(), "激活课程!");
        //设置激活状态
        courseCardEntity.setStatus(CourseCardStatusEnum.ACTIVE.getIndex());
        courseCardDao.update(courseCardEntity);
    }

    /**
     * 外部方法实现
     **/

    @Override
    public List<CourseEntity> findByWait(Long goodsId) {
        return courseDao.findByGoodsIdAndStatus(goodsId, CourseStatusEnum.PRE.getIndex());
    }

    @Override
    public List<CourseEntity> findByWait() {
        return courseDao.findByStatus(CourseStatusEnum.PRE.getIndex());
    }

    @Override
   @Transactional(rollbackFor = Exception.class)
    public CourseCardEntity initCourseCard(Long userId, Long storeId) {
        MallStoreEntity storeEntity = mallStoreDao.get(storeId);
        MallGoodsEntity goodsEntity = mallGoodsDao.get(storeEntity.getGoodsId());
        if (storeEntity.getQuantity() < 1) {
            throw new RRException(goodsEntity.getName() + "库存不足");
        }
        //原价与现价的差价
//        BigDecimal price =  goodsEntity.getOldPrice().subtract(goodsEntity.getNowPrice());
        BigDecimal price = goodsEntity.getProfit();
        //扣减库存
        mallStoreService.decrease(userId, goodsEntity.getId(), 1);
        //生成卡券
        CourseCardEntity courseCardEntity = new CourseCardEntity(UUID.randomUUID().toString(), goodsEntity.getId(), userId, userId, price, CourseCardStatusEnum.NEW.getIndex());
        courseCardDao.save(courseCardEntity);
        //支付
        payByAccount(courseCardEntity);
        return courseCardEntity;
    }

    @Override
    public List<CourseCardEntity> findCardByUserId(Long userId) {
        return courseCardDao.findByUserId(userId);
    }

    @Override
   @Transactional(rollbackFor = Exception.class)
    public CourseCardEntity sendCard(Long userId, Long cardId, Long toUserId) {
        CourseCardEntity cardEntity = courseCardDao.get(cardId);
        if (!cardEntity.getCreateUserId().equals(userId)) {
            throw new RRException("无权限赠送!");
        }
        if (!cardEntity.getUserId().equals(userId)) {
            throw new RRException("已经赠送,请勿重复赠送!");
        }
        //赠送
        cardEntity.setUserId(toUserId);
        courseCardDao.update(cardEntity);
        return cardEntity;
    }

    @Override
   @Transactional(rollbackFor = Exception.class)
    public CourseCardEntity scan(Long userId, String code) {
        CourseCardEntity courseCardEntity = courseCardDao.findByCode(code);
        if (courseCardEntity == null) {
            throw new RRException("请扫描正确的二维码!");
        }
        if (courseCardEntity.getStatus().equals(CourseCardStatusEnum.USED.getIndex())) {
            throw new RRException("卡券已经使用!");
        }
        UserEntity userEntity = userDao.get(userId);
        if (courseCardEntity.getUserId().equals(userId)) {//是自己
            throw new RRException("请勿重复扫码!");
        }
        if (userEntity.getPid().equals(userId)) {//赠送
            courseCardEntity.setUserId(userId);
            courseCardDao.update(courseCardEntity);
        } else { //消费
            //找到有效的报名
            SignEntity signEntity = signDao.findByCardIdNotStatus(courseCardEntity.getId(), CourseStatusEnum.CLOSED.getIndex());
            CourseEntity courseEntity = courseDao.get(signEntity.getCourseId());
            if (courseEntity == null) {
                throw new RRException("没有开班信息");
            }
            if (courseEntity.getStatus().equals(CourseStatusEnum.PRE.getIndex())) {
                throw new RRException("课程尚未开课!");
            }
            //不是管理员
            if (courseEntity.getAdminCode().indexOf(userEntity.getCode()) < 0 && courseEntity.getAdminCode().indexOf(userEntity.getMobile()) < 0) {
                throw new RRException("没有权限!");
            }
            //设置券过期
            courseCardEntity.setStatus(CourseCardStatusEnum.USED.getIndex());
            courseCardDao.update(courseCardEntity);
            //如果报名过 设置签到
            //找出正在报名
//            SignEntity signEntity = signDao.findByCardIdNotStatus(courseCardEntity.getId(), CourseStatusEnum.CLOSED.getIndex());
            if (signEntity != null) {
                signEntity.setStatus(SignStatusEnum.SIGNED.getIndex());
                signDao.update(signEntity);
            }

        }
        return courseCardEntity;
    }

    @Override
   @Transactional(rollbackFor = Exception.class)
    public SignEntity sign(String name, String phone, String remark, Long courserId, Long cardId, Long userId) {
        CourseCardEntity cardEntity = courseCardDao.get(cardId);
        if (cardEntity.getStatus().equals(CourseCardStatusEnum.USED.getIndex())) {
            throw new RRException("卡券已经失效!");
        }
        CourseEntity courseEntity = courseDao.get(courserId);
        if (!courseEntity.getStatus().equals(CourseStatusEnum.PRE.getIndex())) {
            throw new RRException("预报名已经结束!");
        }
        //已经正在进行的报名
        SignEntity signEntity = signDao.findByCardIdNotStatus(cardId, CourseStatusEnum.CLOSED.getIndex());
        if (signEntity != null) {
            throw new RRException("请勿重复报名!");
        }
        signEntity = new SignEntity(courseEntity.getName(), userId, courserId, cardId, SignStatusEnum.NEW.getIndex(), name, phone, remark, new Date(), false);
        signDao.save(signEntity);
        sendCourse(courseEntity);
        return signEntity;
    }

    //通知管理员开课
    private void sendCourse(CourseEntity courseEntity) {
        //统计人数
        List<CourseSumVo> courseSumVos = sumSign(courseEntity.getId());
        if (courseSumVos != null && !courseSumVos.isEmpty()) {
            //预报名人数大于设定的人数 发送通知给管理员
            if (courseEntity.getNumber() != null && courseSumVos.get(0).getNumber() > courseEntity.getNumber()) {
                notcieService.sendCourseToAdmin(courseEntity.getAdminCode(), courseEntity.getName(), courseEntity.getNumber());
            }
        }
    }

    @Autowired
    private NoticeService notcieService;

    @Override
   @Transactional(rollbackFor = Exception.class)
    public SignEntity confirm(Long userId, Long signId) {
        SignEntity signEntity = signDao.get(signId);
        if (!signEntity.getActive()) {
            throw new RRException("报名未通过!");
        }
        if (!signEntity.getStatus().equals(SignStatusEnum.NEW.getIndex())) {
            throw new RRException("请勿重复报名!");
        }
        UserEntity userEntity = userDao.get(userId);
        //既不是自己也不是上级
        if (!signEntity.getUserId().equals(userId) && userEntity.getPid().equals(signEntity.getUserId())) {
            throw new RRException("非法操作!");
        }
        signEntity.setStatus(SignStatusEnum.CONFIRM.getIndex());
        signDao.update(signEntity);
        return signEntity;
    }

    @Override
    public List<CourseSumVo> sumSign(Long courserId) {
        List<CourseSumVo> courseSumVos = new ArrayList<>();
        for (int i = 0; i < SignStatusEnum.values().length; i++) {
            CourseSumVo courseSumVo = new CourseSumVo(SignStatusEnum.indexOf(i), 0, courserId, i);
            courseSumVos.add(courseSumVo);
        }
        List<SignEntity> signEntities = signDao.findByCourseId(courserId);
        signEntities.forEach(signEntity -> {
            for (CourseSumVo courseSumVo : courseSumVos) {
                if (courseSumVo.getStatus() <= signEntity.getStatus()) {
                    courseSumVo.add();
                }
            }
        });
        return courseSumVos;
    }

    @Autowired
    private MallGoodsDao mallGoodsDao;

    @Autowired
    private AccountService accountService;

    @Autowired
    private CourseCardDao courseCardDao;

    @Autowired
    private MallStoreDao mallStoreDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SignDao signDao;

    @Autowired
    private MallStoreService mallStoreService;
}
